package com.micro.platform.example.rsa.controller;

import com.alibaba.fastjson.JSON;
import com.micro.platform.example.rsa.utils.RSACoderUtil;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;


@RestController
@RequestMapping("/rsa")
public class RsaController {
    @RequestMapping("/publicEncryption")
    public Map<String, String> publicEncryption(@RequestParam("data") String data, @RequestParam("publicKey") String publicKey) throws Exception {
        Map<String, String> map = new HashMap<>();
        byte[] bytes = RSACoderUtil.encryptByPublicKey(data, publicKey);
        String s = RSACoderUtil.encryptBASE64(bytes);
        map.put("encryptData", s);
        return map;
    }

    @RequestMapping("/publicDecrypt")
    public Map<String, Object> publicDecrypt(@RequestParam String data, @RequestParam("publicKey") String publicKey) throws Exception {
        Map<String, Object> map = new HashMap<>();
        byte[] bytes = RSACoderUtil.decryptByPublicKey(RSACoderUtil.decryptBASE64(data), publicKey);
        String s = new String(bytes, StandardCharsets.UTF_8);
        map.put("decryptData", JSON.parseObject(s));
        return map;
    }

    @RequestMapping("/privateEncryption")
    public Map<String, String> privateEncryption(@RequestParam("data") String data, @RequestParam("privateKey") String privateKey) throws Exception {
        Map<String, String> map = new HashMap<>();
        byte[] bytes = RSACoderUtil.encryptByPrivateKey(data, privateKey);
        String s = RSACoderUtil.encryptBASE64(bytes);
        map.put("encryptData", s);
        return map;
    }

    @RequestMapping("/privateDecrypt")
    public Map<String, Object> privateDecrypt(@RequestParam String data, @RequestParam("privateKey") String privateKey) throws Exception {
        Map<String, Object> map = new HashMap<>();
        byte[] bytes = RSACoderUtil.decryptByPrivateKey(RSACoderUtil.decryptBASE64(data), privateKey);
        String s = new String(bytes, StandardCharsets.UTF_8);
        map.put("decryptData", JSON.parseObject(s));
        return map;
    }
}
